
package cn.xxl.cordova.iscanner;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONException;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import com.android.barcodescandemo.ScannerInerface;

public class IScanner extends CordovaPlugin {

    private ScannerInerface mScanner;

    private BroadcastReceiver mScanReceiver;
    
    private static final String RES_ACTION = "android.intent.action.SCANRESULT";

    @Override
    public void initialize(final CordovaInterface cordova, CordovaWebView webView) {
        super.initialize(cordova, webView);

        //mScanner = new ScannerInerface(this.cordova.getActivity().getApplicationContext());
        mScanner = new ScannerInerface(this.cordova.getActivity());
        //mScanner.open();
        mScanner.enablePlayBeep(true);
        mScanner.enablePlayVibrate(false);
        // mScanner.enablShowAPPIcon(false);
        // mScanner.enablShowNoticeIcon(false);
        
        mScanner.lockScanKey();

        mScanner.setOutputMode(1);
        
        IntentFilter intentFilter = new IntentFilter(RES_ACTION);

        mScanReceiver = new ScannerResultReceiver();
        webView.getContext().registerReceiver(mScanReceiver, intentFilter);
    }

    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {

        if (action.equals("open")) {
            mScanner.open();
            return true;
        }

        if (action.equals("close")) {
            mScanner.close();
            return true;
        }

        return false;
    }

    private class ScannerResultReceiver extends BroadcastReceiver{
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(RES_ACTION)) {
                final String scanData = intent.getStringExtra("value");

                try {
                    cordova.getActivity().runOnUiThread(new Runnable() {
                        public void run() {
                            String jsEvent = String.format(
                                    "cordova.fireDocumentEvent('iScanner.DataReceived',{'scanData':'%s'})",
                                    scanData);
                            webView.sendJavascript(jsEvent);
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void onDestroy() {
        mScanner.close();
        super.onDestroy();
    }
}